﻿package com.badibadi.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import com.badibadi.infos.Chat_History_Message_Model;
import com.badibadi.infos.Chat_Message_Model;
import com.badibadi.infos.Img;
import com.badibadi.infos.Results;
import com.badibadi.logic.ImgFileListActivity;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.EditTextTools;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.IOUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.RegexUtils;
import com.badibadi.mytools.SoundMeter;
import com.badibadi.mytools.SoundUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.mytools.XUtils;
import com.badibadi.socket.Send_Geshi_Tool;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.SinaExpressionActivity;
//import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.test.pic.UpYuYinTestActivity;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

//chat_setting smile_btn voice  wx2_23 replaceAllReplaceToPath ll_tupian 接收到的结果是:{"retmsg":"\/Public\/Uploads\/amr\/2014-12\/549160e5d21d46.28234116.amr","ret":true,"moredata":false}
public class ChatActivity extends BaseActivity implements OnClickListener,
		OnTouchListener, IXListViewListener {

	private static final String TAG = "ChatActivity";
	private static final int C_DINGWEI = 1;
	private static final int C_TUPIAN = 5;
	private ImageButton chat_add_btn;
	private boolean chat_add_btn_isOpen = false;
	private RelativeLayout bottom_view;
	private Button chat_setting;
	private ImageButton smile_btn;
	private Button chat_back;
	private XListView chat_message_list;
	private Chat_List_Adapter list_Adapter;
	private List<Chat_Message_Model> chat_Message_Models;
	private Chat_Message_Model message_Model;
	private TextView chat_liaotian_name;
	private int Page = 0;
	private String uid;
	private String u_head;
	private Results results;
	private List<Chat_History_Message_Model> message_Models;
	/**
	 * 语音按钮
	 */
	private ImageView voicebtn;
	private EditText chat;
	private LinearLayout chat_group;
	private LinearLayout anzhu_tishi;// 提示的外层LinearLayout
	/**
	 * 发送按钮
	 */
	private FrameLayout SendButton;
	private String id, name, head;// 对方的id,名字,头像

	/**
	 * 软键盘开启还是关闭（实时监听） anzhu_tishi
	 */
	private boolean KeyBoardIsOpen = false;

	// 下面的是语音的
	private boolean isShosrt = false;
	private long startVoiceT, endVoiceT;
	private String voiceName;
	private static final int POLL_INTERVAL = 1;

	private long startHaomiao;
	private long endHaomiao;
	private int miaoshu;

	private com.badibadi.mytools.SoundMeter mSensor;
	ArrayList<String> htmp_list;
	private Calendar calendar;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
				// .fengzhuang_Login(Utils.getUid(ChatActivity.this),
				// Utils.getPwd(ChatActivity.this)));
				try {
					Utils.ExitProgress_hen(ChatActivity.this);
					Utils.showMessage(ChatActivity.this, getResources()
							.getString(R.string.l_net_error));
					chat_message_list.stopRefresh();
					chat_message_list.stopLoadMore();
					chat_message_list.setRefreshTime(""
							+ getResources().getString(R.string.ganggang));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 2:
				try {
					message_Model = (Chat_Message_Model) msg.getData()
							.getSerializable("me");
					chat_Message_Models.add(message_Model);
					list_Adapter.notifyDataSetChanged();
					chat_message_list
							.setSelection(chat_Message_Models.size() - 1);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 3:
				try {
					message_Model = (Chat_Message_Model) msg.getData()
							.getSerializable("you");
					chat_Message_Models.add(message_Model);
					list_Adapter.notifyDataSetChanged();
					chat_message_list
							.setSelection(chat_Message_Models.size() - 1);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 4:
				try {
					finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 5:// 语音 上传成功之后返回路径
				try {
					Utils.ExitProgress_hen(ChatActivity.this);
					String path = msg.getData().getString("msg");
					int miaoshu = msg.getData().getInt("miaoshu", 0);
					if (path != null) {
						if (Send_Geshi_Tool.socketThread != null) {
							Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
									.fenzhuang_Send(
											Utils.getUid(ChatActivity.this),
											Utils.getu_Name(ChatActivity.this),
											id, name, path + "," + miaoshu));
							chat.setText("");
						} else {
							Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
									error_handler, ChatActivity.this);
							handler.sendEmptyMessageDelayed(20, 1000);
							// Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							// .fenzhuang_Send(
							// Utils.getUid(ChatActivity.this),
							// Utils.getu_Name(ChatActivity.this),
							// id, name, path + "," + miaoshu));
							// Toast.makeText(getApplicationContext(),
							// "socket为空",
							// 0).show();
						}
						// Utils.showMessage(ChatActivity.this, "发送消息");
					}

				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 6:// 语音 上传中
				try {
					int content = msg.getData().getInt("msg");
					Utils.setProgress_hen(content);
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 7:
				try {
					Utils.ExitProgress_hen(ChatActivity.this);
					Utils.showMessage(ChatActivity.this, getResources()
							.getString(R.string.l_xa10));
					chat_message_list.stopRefresh();
					chat_message_list.stopLoadMore();
					chat_message_list.setRefreshTime(""
							+ getResources().getString(R.string.ganggang));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 8:
				try {
					Utils.ExitProgress_hen(ChatActivity.this);
					chat_message_list.stopRefresh();
					chat_message_list.stopLoadMore();
					chat_message_list.setRefreshTime(""
							+ getResources().getString(R.string.ganggang));
					chat_Message_Models.addAll(0, zhuhe(message_Models));
					list_Adapter.notifyDataSetChanged();
					chat_message_list
							.setSelection(chat_Message_Models.size() - 1);
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 9:
				if (Send_Geshi_Tool.socketThread != null) {
					Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							.fengzhuang_Login(Utils.getUid(ChatActivity.this),
									Utils.getPwd(ChatActivity.this)));
					Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							.fenzhuang_Send(Utils.getUid(ChatActivity.this),
									Utils.getu_Name(ChatActivity.this), id,
									name, chat.getText().toString().trim()));
					chat.setText("");
				} else {
					Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
							error_handler, ChatActivity.this);
					handler.sendEmptyMessageDelayed(20, 1000);
				}
				break;
			case 2000:
				Utils.ExitPrgress(ChatActivity.this);
				Utils.ExitProgress_hen(ChatActivity.this);
				Utils.showMessage(ChatActivity.this,
						getResources().getString(R.string.l_xb18));
				String temp_path = msg.getData().getString("path");
				htmp_list = new ArrayList<String>();
				htmp_list.addAll(fenge(temp_path));
				// LogUtils.d("y=1");
				// StringBuffer buff = new StringBuffer("");
				for (int i = 0; i < htmp_list.size(); i++) {
					// LogUtils.d("y=2" + htmp_list.get(i).toString());

					// activity_mail_content.setText(activity_mail_content
					// .getText().toString() + list3.get(i));
					// activity_mail_content.setSelection(activity_mail_content
					// .getText().toString().length());
					// buff.append(htmp_list.get(i) + " ");
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						   
					}
					if (Send_Geshi_Tool.socketThread != null) {
						Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
								.fenzhuang_Send(
										Utils.getUid(ChatActivity.this),
										Utils.getu_Name(ChatActivity.this), id,
										name, htmp_list.get(i)));
						chat.setText("");
					} else {
						Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
								error_handler, ChatActivity.this);
						handler.sendEmptyMessageDelayed(20, 1000);
						break;
					}

				}
				// LogUtils.d("y=3");
				//    
				// if (Send_Geshi_Tool.socketThread != null) {
				// Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
				// .fenzhuang_Send(Utils.getUid(ChatActivity.this),
				// Utils.getu_Name(ChatActivity.this), id,
				// name, buff.toString()));
				// chat.setText("");
				// htmp_list = new ArrayList<String>();
				// } else {
				// Toast.makeText(getApplicationContext(), "socket为空", 0)
				// .show();
				// htmp_list = new ArrayList<String>();
				// }
				break;
			case 20:
				if (Send_Geshi_Tool.socketThread != null) {
					Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							.fengzhuang_Login(Utils.getUid(ChatActivity.this),
									Utils.getPwd(ChatActivity.this)));
				}
				break;
			default:
				break;
			}
		}
	};

	private ArrayList<String> fenge(String ds) {
		String dg[] = ds.split(",");
		ArrayList<String> list2 = new ArrayList<String>();
		if (dg != null) {
			for (int i = 0; i < dg.length; i++) {
				// <img
				// src='http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/7a/shenshou_thumb.gif'
				// />"
				list2.add("<img style='max-width:140px;' src='"
						+ Constants.BadiDownImgUrl + dg[i] + "' />");
			}
		}
		return list2;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.chat);
		htmp_list = new ArrayList<String>();
		calendar = Calendar.getInstance();
		init();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Constants.temp_socket_id = id;
		Constants.Chat_handler = handler;
		Constants.Close_Chat_handler = handler;
	}

	private void ChuLi_New_Mess(String id) {
		for (int i = 0; i < Send_Geshi_Tool.chat_Message_Models.size(); i++) {
			//    
			// "新消息的id是:"
			// + Send_Geshi_Tool.chat_Message_Models.get(i)
			// .getNew_mess_uid());
			if (Send_Geshi_Tool.chat_Message_Models.get(i).getNew_mess_uid()
					.equals(id)) {
				chat_Message_Models.add(Send_Geshi_Tool.chat_Message_Models
						.get(i));
				// Send_Geshi_Tool.chat_Message_Models.remove(i);
			} else {
				//    
			}
		}
	}

	// private List<Chat_Message_Model> fanxu(List<Chat_Message_Model> models) {
	// List<Chat_Message_Model> models_1 = new ArrayList<Chat_Message_Model>();
	// for (int i = models.size() - 1; i > 0; --i) {
	// models_1.add(models.get(i));
	// }
	// return models_1;
	// }

	private void Remove_New_Mess(String id) {
		for (int i = 0; i < Send_Geshi_Tool.chat_Message_Models.size(); i++) {
			if (Send_Geshi_Tool.chat_Message_Models.get(i).getNew_mess_uid()
					.equals(id)) {
				Send_Geshi_Tool.chat_Message_Models.remove(i);
				//    
				// + Send_Geshi_Tool.chat_Message_Models.get(i)
				// .getNew_mess_uid() + " " + id);
			} else {
				//    
			}
		}
	}

	private List<Chat_Message_Model> zhuhe(
			List<Chat_History_Message_Model> messaged) {
		List<Chat_Message_Model> list = new ArrayList<Chat_Message_Model>();
		for (int i = messaged.size() - 1; i >= 0; --i) {
			Chat_Message_Model mes = new Chat_Message_Model();
			if (messaged.get(i).getId().equals(uid)) {
				mes.setMe_or_you("1");
				mes.setChat_img(u_head);
			} else if (messaged.get(i).getId().equals(id)) {
				mes.setMe_or_you("2");
				mes.setChat_img(head);
			} else {
				mes.setMe_or_you("0");
				mes.setChat_img(head);
			}
			mes.setChat_message(messaged.get(i).getMsg());
			mes.setChat_name(messaged.get(i).getNickName());
			mes.setChat_time(messaged.get(i).getTime());
			list.add(mes);
		}
		return list;
	}

	private void init() {
		// TODO Auto-generated method stub
		mSensor = new SoundMeter();
		// 按住音频提示框不松后的提示TextView
		try {
			id = getIntent().getStringExtra("id");
			name = getIntent().getStringExtra("name");
			head = getIntent().getStringExtra("head");
			uid = Utils.getUid(ChatActivity.this);
			u_head = Utils.getu_Head(ChatActivity.this);
		} catch (Exception e) {
			   
		}
		chat_liaotian_name = (TextView) this
				.findViewById(R.id.chat_liaotian_name);
		chat_liaotian_name.setText(name);
		chat_back = (Button) this.findViewById(R.id.chat_back);
		chat_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// Toast.makeText(getApplicationContext(), "关闭", 0).show();
				if (Send_Geshi_Tool.socketThread != null) {
					Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							.fengzhuang_Send_yihuifu(id,
									Utils.getUid(ChatActivity.this)));
					//    
					// Send_Geshi_Tool.fengzhuang_Send_yihuifu(
					// Utils.getUid(ChatActivity.this), id));
					//    
				} else {
					//    
				}
				Remove_New_Mess(id);
				ChatActivity.this.finish();
			}
		});
		message_Models = new ArrayList<Chat_History_Message_Model>();
		chat_Message_Models = new ArrayList<Chat_Message_Model>();
		// ChuLi_New_Mess(id);
		//    
		anzhu_tishi = (LinearLayout) this.findViewById(R.id.anzhu_tishi);
		// anzhu_tishi.setOnTouchListener(this);
		chat_group = (LinearLayout) this.findViewById(R.id.chat_group);
		chat_group.setOnTouchListener(this);
		chat_group.setSelected(true);
		chat_add_btn = (ImageButton) this.findViewById(R.id.chat_add_btn);
		bottom_view = (RelativeLayout) this.findViewById(R.id.bottom_shitu);
		chat_add_btn.setOnClickListener(ChatActivity.this);
		chat_setting = (Button) this.findViewById(R.id.chat_setting);
		chat_setting.setOnClickListener(ChatActivity.this);

		smile_btn = (ImageButton) findViewById(R.id.smile_btn);
		smile_btn.setOnClickListener(this);
		// 语音
		voicebtn = (ImageView) findViewById(R.id.voice);
		voicebtn.setOnClickListener(this);
		// 发送
		SendButton = (FrameLayout) this.findViewById(R.id.Send);
		SendButton.setOnClickListener(this);

		chat_message_list = (XListView) this
				.findViewById(R.id.chat_message_list);
		chat_message_list.setXListViewListener(this);
		chat_message_list.setPullLoadEnable(false);
		chat_message_list.setPullRefreshEnable(true);
		list_Adapter = new Chat_List_Adapter(ChatActivity.this);
		chat_message_list.setAdapter(list_Adapter);
		chat_message_list.startLoadMore();
		chat = (EditText) this.findViewById(R.id.chat);
		this.findViewById(R.id.ll_tupian).setOnClickListener(this);
		this.findViewById(R.id.ll_address).setOnClickListener(this);

		/**
		 * 判断键盘是打开还是关闭
		 * （原理就是根据一个layout，通常是全屏的layout），如果键盘打开会压缩这个layout，那么根据这个压缩的全屏的layout
		 * -压缩的layout的高来判断键盘是否打开
		 */
		final View activityRootView = findViewById(R.id.root_layout);
		chat.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if ("".equals(s.toString().trim()) != true) {
					SendButton.setVisibility(View.VISIBLE);
					voicebtn.setVisibility(View.GONE);
				} else if ("".equals(s.toString().trim()) == true) {
					SendButton.setVisibility(View.GONE);
					voicebtn.setVisibility(View.VISIBLE);
				}
			}
		});

		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					private int preHeight = 0;

					@Override
					public void onGlobalLayout() {
						// 这里获取的activityRootView.getRootView().getHeight()
						// 是根视图，根视图不会变化
						//    
						// " activityRootView.getRootView().getHeight()-->"
						// + activityRootView.getRootView()
						// .getHeight());
						// 这里获取的activityRootView.getHeight()
						// 是View的高,高是根据键盘压缩会发生变化
						//    
						// + activityRootView.getHeight());
						int heightDiff = activityRootView.getRootView()
								.getHeight() - activityRootView.getHeight();
						//    ("height differ = " + heightDiff);
						// 在数据相同时，减少发送重复消息。因为实际上在输入法出现时会多次调用这个onGlobalLayout方法。
						if (preHeight == heightDiff) {
							return;
						}
						preHeight = heightDiff;
						//    
						// 这里的200可能会根据不同的手机来适应不同的
						if (heightDiff > 200) {
							//    ("input method shown!");
							// Toast.makeText(getApplicationContext(), "键盘已经打开",
							// Toast.LENGTH_SHORT).show();
							KeyBoardIsOpen = true;
						} else {
							// Toast.makeText(getApplicationContext(), "键盘已经关闭",
							// Toast.LENGTH_SHORT).show();
							KeyBoardIsOpen = false;
						}
					}
				});
		Timer_dingshi(Utils.getUid(ChatActivity.this), id);
	}

	private void Timer_dingshi(final String id, final String toid) {
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if (Send_Geshi_Tool.socketThread != null) {
					Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							.fengzhuang_Send_yihuifu(toid, id));
					//    
					// Send_Geshi_Tool.fengzhuang_Send_yihuifu(toid, id));
					//    
				} else {
					//    
				}
				timer.cancel();
			}
		}, 1500);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Remove_New_Mess(id);
		Constants.temp_socket_id = null;
		// stopSocket();// 临时使用
	}

	/**
	 * 可见或不可见之间切换
	 */
	private void BottomBtnVisible() {
		if (chat_add_btn_isOpen != true) {
			chat_add_btn_isOpen = true;
			bottom_view.setVisibility(View.VISIBLE);
			chat_add_btn.setBackgroundResource(R.drawable.add);
		} else if (chat_add_btn_isOpen != false) {
			chat_add_btn_isOpen = false;
			bottom_view.setVisibility(View.GONE);
			chat_add_btn.setBackgroundResource(R.drawable.add_no);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.chat_add_btn:
			BottomBtnVisible();
			break;
		case R.id.chat_setting:
			Intent intent = new Intent(ChatActivity.this,
					ChatSettingActivity.class);
			intent.putExtra("fid", id);
			startActivity(intent);
			break;
		case R.id.smile_btn:
			Intent intent1 = new Intent(ChatActivity.this,
					SinaExpressionActivity.class);
			startActivityForResult(intent1, 13);
			break;
		case R.id.voice:
			if (voicebtn.isSelected() == true) {
				// smile_btn.setSelected(false);
				smile_btn.setVisibility(View.VISIBLE);
				voicebtn.setSelected(false);
				chat.setVisibility(View.VISIBLE);
				anzhu_tishi.setVisibility(View.GONE);
				EditTextTools.CloseOrConsultingEvaluation(chat);
			} else if (voicebtn.isSelected() == false) { // 如果键盘是打开的

				if (KeyBoardIsOpen == true) {
					EditTextTools.CloseOrConsultingEvaluation(chat);

				} else {

				}
				smile_btn.setVisibility(View.GONE);
				smile_btn.setSelected(false);
				anzhu_tishi.setVisibility(View.VISIBLE);
				chat.setVisibility(View.GONE);
				voicebtn.setSelected(true);
			}

			break;
		case R.id.Send:
			//    ("发出去的消息是:"
			// + Send_Geshi_Tool.fenzhuang_Send(
			// Utils.getUid(ChatActivity.this), "谢谢你的爱", "1",
			// "小小成诗", chat.getText().toString().trim()));
			if (Send_Geshi_Tool.socketThread != null) {
				if (chat.getText().toString().trim().length() > 200) {
					String aa = String.format(
							getResources().getString(R.string.wx2_23), "200");
					Utils.showMessage(ChatActivity.this, "" + aa);
				} else {
					Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
							.fenzhuang_Send(Utils.getUid(ChatActivity.this),
									Utils.getu_Name(ChatActivity.this), id,
									name, chat.getText().toString().trim()));
					chat.setText("");
					// Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
					// error_handler, ChatActivity.this);
					// handler.sendEmptyMessageDelayed(5, 1000);
				}

			} else {
				// Toast.makeText(getApplicationContext(), "socket为空",
				// 0).show();
				// Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
				// error_handler, ChatActivity.this);
				// handler.sendEmptyMessageDelayed(9, 1000);
				Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
						error_handler, ChatActivity.this);
				handler.sendEmptyMessageDelayed(20, 1000);
			}
			// Utils.showMessage(ChatActivity.this, "发送消息");
			break;
		case R.id.ll_tupian:
			// zxdfc
			Intent intent3 = new Intent(ChatActivity.this,
					ImgFileListActivity.class);
			intent3.putExtra("panduan", "no_set");
			// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(intent3, C_TUPIAN);
			break;
		case R.id.ll_address:
			Intent intent2 = new Intent(ChatActivity.this,
					PunchCardActivity.class);
			startActivityForResult(intent2, C_DINGWEI);
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == 4) {
			if (Send_Geshi_Tool.socketThread != null) {
				Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
						.fengzhuang_Send_yihuifu(id,
								Utils.getUid(ChatActivity.this)));
				//    
				// Send_Geshi_Tool.fengzhuang_Send_yihuifu(
				// Utils.getUid(ChatActivity.this), id));
				//    
			} else {
				//    
			}
			Remove_New_Mess(id);
			ChatActivity.this.finish();
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 13 && arg1 == SinaExpressionActivity.ACTIVITY_BIAOQING) {
			if (arg2 != null) {
				// String con = arg2.getExtras().getString("result");
				// String con1 = chat.getText().toString();
				// String con2 = con1 + con;
				// chat.setText(con2);
				String content2 = arg2.getStringExtra("result");
				int index = chat.getSelectionStart();
				Editable edit = chat.getEditableText();
				edit.insert(index, content2);

			}

		}
		// if(arg0==C_DINGWEI && )
		if (arg0 == C_DINGWEI && arg1 == 2) {
			if (arg2 != null) {
				String address = arg2.getStringExtra("result");
				String Longitude = arg2.getStringExtra("Longitude");
				String Latitude = arg2.getStringExtra("Latitude");
				if (address != null) {
					//    
					if (Send_Geshi_Tool.socketThread != null) {
						Send_Geshi_Tool.socketThread.Send(Send_Geshi_Tool
								.fenzhuang_Send(
										Utils.getUid(ChatActivity.this),
										Utils.getu_Name(ChatActivity.this), id,
										name, address));
						chat.setText("");
					} else {
						Send_Geshi_Tool.startSocket(mhandler, mhandlerSend,
								error_handler, ChatActivity.this);
						handler.sendEmptyMessageDelayed(20, 1000);
						// Toast.makeText(getApplicationContext(), "socket为空",
						// 0)
						// .show();
					}
				}
			}
		}
		// 图片
		if (arg0 == C_TUPIAN && arg1 == 5) {
			ArrayList<String> filelist = arg2.getStringArrayListExtra("files");

			// addressModels = new ArrayList<TempIMGAddressModel>();
			// if (filelist != null && !filelist.isEmpty()) {
			// for (int i = 0; i < filelist.size(); i++) {
			// TempIMGAddressModel model = new TempIMGAddressModel();
			// model.setImg_address(filelist.get(i));
			// addressModels.add(model);
			// }
			// }
			// addressModels_main.addAll(addressModels);
			// adapter.notifyDataSetChanged();
			// Utils.showPrgress(SendDynamicActivity.this);
			// Utils.showMessage(Club_SendDynamicActivity.this,
			// getResources()
			// .getString(R.string.l_xb46));
			// for (int i = 0; i < filelist.size(); i++) {
			//    
			// }
			XUtils.UpImg_ceshi_douhaoXUtils(filelist, ChatActivity.this,
					handler);
			// for (int i = 0; i < filelist.size(); i++) {
			//    ("获取到的图片地址是:" + filelist.get(i));
			// }
		}
	}

	class Chat_List_Adapter extends BaseAdapter {

		private Context context;
		private DisplayImageOptions options;

		public Chat_List_Adapter(Context c) {
			context = c;
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.ic_stub)
					.showImageForEmptyUri(R.drawable.noimage)
					.showImageOnFail(R.drawable.noimage).cacheInMemory()
					.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5))
					.build();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return chat_Message_Models.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return chat_Message_Models.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			LayoutInflater inflater = LayoutInflater.from(context);
			// String a = "/Public/Uploads/amr/";
			// String a = "/Public/music";
			String a = Constants.YuyingQianZui;
			int type = -1;// 种类 0.语音 1.消息没有语言
			if (chat_Message_Models.get(arg0).getChat_message().startsWith(a) == true) {
				arg1 = inflater.inflate(R.layout.chat_sound1, null);
				type = 0;
			} else {
				arg1 = inflater.inflate(R.layout.char_list_item, null);
				type = 1;
			}
			LinearLayout char_list_itme_me = (LinearLayout) arg1
					.findViewById(R.id.char_list_itme_me);
			ImageView char_list_item_img_me = (ImageView) arg1
					.findViewById(R.id.char_list_item_img_me);
			// TextView char_list_item_name_me = (TextView) arg1
			// .findViewById(R.id.char_list_item_name_me);
			TextView char_list_item_message_me = (TextView) arg1
					.findViewById(R.id.char_list_item_message_me);
			TextView char_list_item_time_me = (TextView) arg1
					.findViewById(R.id.char_list_item_time_me);

			LinearLayout char_list_itme_you = (LinearLayout) arg1
					.findViewById(R.id.char_list_itme_you);
			ImageView char_list_item_img_you = (ImageView) arg1
					.findViewById(R.id.char_list_item_img_you);
			// TextView char_list_item_name_you = (TextView) arg1
			// .findViewById(R.id.char_list_item_name_you);
			TextView char_list_item_message_you = (TextView) arg1
					.findViewById(R.id.char_list_item_message_you);
			TextView char_list_item_time_you = (TextView) arg1
					.findViewById(R.id.char_list_item_time_you);

			LinearLayout chat_item_click1 = (LinearLayout) arg1
					.findViewById(R.id.chat_item_click1);
			LinearLayout chat_item_click2 = (LinearLayout) arg1
					.findViewById(R.id.chat_item_click2);
			if (chat_Message_Models.get(arg0).getMe_or_you().equals("1")) {// 如果是自己的
				char_list_itme_me.setVisibility(View.VISIBLE);
				char_list_itme_you.setVisibility(View.GONE);
				try {
					ImageLoader.getInstance().displayImage(
							Constants.BadiDownImgUrl
									+ Utils.getu_Head(ChatActivity.this)
									+ Constants.appPhoto4img,
							char_list_item_img_me, options);
					// char_list_item_name_me.setText(chat_Message_Models
					// .get(arg0).getChat_name());
					if (type == 1) {// 如果是消息
						new HtmlUtils(ChatActivity.this,
								char_list_item_message_me, chat_Message_Models
										.get(arg0).getChat_message())
								.showTextView();
						char_list_item_message_me
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub

										List<String> list = RegexUtils
												.getImgSrc(chat_Message_Models
														.get(arg0)
														.getChat_message());
										if (list != null && !list.isEmpty()) {
											Intent intent = new Intent(
													ChatActivity.this,
													ShowViewPagerActivity.class);
											intent.putStringArrayListExtra(
													"pic",
													(ArrayList<String>) list);
											startActivity(intent);
										} else {

										}

									}
								});

					} else if (type == 0) {// 如果是语音
						final String[] message = chat_Message_Models.get(arg0)
								.getChat_message().split(",");
						// for (int i = 0; i < message.length; i++) {
						//    
						// }

						if (message.length == 2) {
							char_list_item_message_me.setText("" + message[1]);
						}
						ImageView voice2 = (ImageView) arg1
								.findViewById(R.id.voice2);
						voice2.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								SoundUtils sound = new SoundUtils(
										ChatActivity.this);

								// 这里下载语言
								sound.downloadSound(message[0]);
								//    

							}
						});
						chat_item_click2
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										SoundUtils sound = new SoundUtils(
												ChatActivity.this);

										// 这里下载语言
										sound.downloadSound(message[0]);
										//    
									}
								});
					}

					// char_list_item_message_me.setText(chat_Message_Models.get(
					// arg0).getChat_message());
					if (Utils.panduan_is_cunzai(chat_Message_Models.get(arg0)
							.getChat_time(), ":")) {
						char_list_item_time_me.setText(chat_Message_Models.get(
								arg0).getChat_time());
					} else {
						char_list_item_time_me.setText(Utils.Get_Data(
								chat_Message_Models.get(arg0).getChat_time(),
								"HH:mm", "000"));
					}
				} catch (Exception e) {
					   
				}
			} else if (chat_Message_Models.get(arg0).getMe_or_you().equals("2")) {// 如果是别人的
				char_list_itme_me.setVisibility(View.GONE);
				char_list_itme_you.setVisibility(View.VISIBLE);
				try {
					ImageLoader.getInstance().displayImage(
							Constants.BadiDownImgUrl + head
									+ Constants.appPhoto4img,
							char_list_item_img_you, options);
					// char_list_item_name_you.setText(chat_Message_Models.get(
					// arg0).getChat_name());
					if (type == 1) {
						new HtmlUtils(ChatActivity.this,
								char_list_item_message_you, chat_Message_Models
										.get(arg0).getChat_message())
								.showTextView();
						char_list_item_message_you
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub

										List<String> list = RegexUtils
												.getImgSrc(chat_Message_Models
														.get(arg0)
														.getChat_message());
										if (list != null && !list.isEmpty()) {
											Intent intent = new Intent(
													ChatActivity.this,
													ShowViewPagerActivity.class);
											intent.putStringArrayListExtra(
													"pic",
													(ArrayList<String>) list);
											startActivity(intent);
										} else {

										}

									}
								});
					} else if (type == 0) {

						final String[] message = chat_Message_Models.get(arg0)
								.getChat_message().split(",");
						if (message.length == 2) {
							char_list_item_message_you.setText("" + message[1]);
						}
						ImageView voice = (ImageView) arg1
								.findViewById(R.id.voice);

						voice.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								SoundUtils sound = new SoundUtils(
										ChatActivity.this);
								sound.downloadSound(message[0]);

							}
						});
						chat_item_click1 // 扩大点击范围而已
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										SoundUtils sound = new SoundUtils(
												ChatActivity.this);

										// 这里下载语言
										sound.downloadSound(message[0]);
										//    
									}
								});
					}

					// char_list_item_message_you.setText(chat_Message_Models.get(
					// arg0).getChat_message());
					if (Utils.panduan_is_cunzai(chat_Message_Models.get(arg0)
							.getChat_time(), ":")) {
						char_list_item_time_you.setText(chat_Message_Models
								.get(arg0).getChat_time());
					} else {
						char_list_item_time_you.setText(Utils.Get_Data(
								chat_Message_Models.get(arg0).getChat_time(),
								"HH:mm", "000"));
					}
					//    
					// + chat_Message_Models.get(arg0).getChat_time());

				} catch (Exception e) {
					   
				}
			} else if (chat_Message_Models.get(arg0).getMe_or_you().equals("0")
					&& chat_Message_Models.get(arg0).getNew_mess_uid()
							.equals(id)) {
				char_list_itme_me.setVisibility(View.GONE);
				char_list_itme_you.setVisibility(View.VISIBLE);
				try {
					ImageLoader.getInstance().displayImage(
							Constants.BadiDownImgUrl + head
									+ Constants.appPhoto4img,
							char_list_item_img_you, options);
					// char_list_item_name_you.setText(chat_Message_Models.get(
					// arg0).getChat_name());

					if (type == 1) {
						new HtmlUtils(ChatActivity.this,
								char_list_item_message_you, chat_Message_Models
										.get(arg0).getChat_message())
								.showTextView();
						char_list_item_message_you
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub

										List<String> list = RegexUtils
												.getImgSrc(chat_Message_Models
														.get(arg0)
														.getChat_message());
										if (list != null && !list.isEmpty()) {
											Intent intent = new Intent(
													ChatActivity.this,
													ShowViewPagerActivity.class);
											intent.putStringArrayListExtra(
													"pic",
													(ArrayList<String>) list);
											startActivity(intent);
										} else {

										}

									}
								});
					} else if (type == 0) {
						final String[] message = chat_Message_Models.get(arg0)
								.getChat_message().split(",");
						if (message.length == 2) {
							char_list_item_message_you.setText("" + message[1]);
						}
						ImageView voice = (ImageView) arg1
								.findViewById(R.id.voice);
						voice.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								SoundUtils sound = new SoundUtils(
										ChatActivity.this);
								sound.downloadSound(message[0]);

							}
						});
						chat_item_click1 // 扩大点击范围而已
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										SoundUtils sound = new SoundUtils(
												ChatActivity.this);

										// 这里下载语言
										sound.downloadSound(message[0]);
										//    
									}
								});
						chat_item_click2 // 扩大点击范围而已
								.setOnClickListener(new View.OnClickListener() {

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										SoundUtils sound = new SoundUtils(
												ChatActivity.this);

										// 这里下载语言
										sound.downloadSound(message[0]);
										//    
									}
								});
					}

					// new HtmlUtils(ChatActivity.this,
					// char_list_item_message_you, chat_Message_Models
					// .get(arg0).getChat_message())
					// .showTextView();

					// char_list_item_message_you.setText(chat_Message_Models.get(
					// arg0).getChat_message());
					if (chat_Message_Models.get(arg0).getChat_time() != null) {
						char_list_item_time_you.setText(Utils.Get_Data(
								Utils.getStringMillis_quan(chat_Message_Models
										.get(arg0).getChat_time(), calendar)
										+ "", "HH:mm", "000"));
					} else {
						//    
						char_list_item_time_you.setText(Utils
								.Get_System_Time("HH:mm"));
					}

				} catch (Exception e) {
					   
				}
			} else {
				char_list_itme_me.setVisibility(View.GONE);
				char_list_itme_you.setVisibility(View.GONE);
			}

			return arg1;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		try {
			if (v.getId() == R.id.chat_group) {
				switch (event.getAction()) {
				case KeyEvent.ACTION_UP:
					//    
					// IOUtils.getSaveObjectPath(context, filename)
					this.findViewById(R.id.chat_group).setBackgroundResource(
							R.drawable.select_shape_edittext_white_bg);
					// if (event.getY() >= del_Y
					// && event.getY() <= del_Y + del_re.getHeight()
					// && event.getX() >= del_x
					// && event.getX() <= del_x + del_re.getWidth()) {
					this.findViewById(R.id.voice_rcd_hint_rcding)
							.setVisibility(View.GONE);
					this.findViewById(R.id.img1).setVisibility(View.VISIBLE);
					this.findViewById(R.id.del_re).setVisibility(View.GONE);
					stop();
					endHaomiao = System.currentTimeMillis();
					// flag = 1;
					File file = new File(
							IOUtils.getSaveObjectPath(ChatActivity.this) + "/"
									+ voiceName);
					//    ("DIERCI=" + file.getPath());

					//    
					if (file.exists()) {
						//    

						UpSound(IOUtils.getSaveObjectPath(ChatActivity.this)
								+ "/" + voiceName);
					} else {

					}
					break;

				case KeyEvent.ACTION_MULTIPLE:
					//    
					break;
				case KeyEvent.ACTION_DOWN: {
					//    
					stop();
					this.findViewById(R.id.chat_group).setBackgroundResource(
							R.drawable.voice_rcd_btn_pressed);
					this.findViewById(R.id.rcChat_popup).setVisibility(
							View.VISIBLE);
					this.findViewById(R.id.voice_rcd_hint_loading)
							.setVisibility(View.VISIBLE);// rcChat_popup
															// chat_message_list
					this.findViewById(R.id.voice_rcd_hint_rcding)
							.setVisibility(View.GONE);
					this.findViewById(R.id.voice_rcd_hint_tooshort)
							.setVisibility(View.GONE);
					handler.postDelayed(new Runnable() {
						public void run() {
							if (!isShosrt) {
								ChatActivity.this.findViewById(
										R.id.voice_rcd_hint_loading)
										.setVisibility(View.GONE);
								ChatActivity.this.findViewById(
										R.id.voice_rcd_hint_rcding)
										.setVisibility(View.VISIBLE);
							}
						}
					}, 1);
					this.findViewById(R.id.img1).setVisibility(View.VISIBLE);
					this.findViewById(R.id.del_re).setVisibility(View.GONE);
					startVoiceT = SystemClock.currentThreadTimeMillis();
					voiceName = startVoiceT + ".amr";
					startHaomiao = System.currentTimeMillis();
					start(voiceName);
					// flag = 2;

				}
					break;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			// Utils.showMessage(ChatActivity.this, "录音时间过短");
			// this.findViewById(R.id.voice_rcd_hint_loading).setVisibility(View.GONE);
		}

		return true;
	}

	private void start(String name) {
		mSensor.start(ChatActivity.this, name);
		handler.postDelayed(mPollTask, POLL_INTERVAL);
	}

	private Runnable mPollTask = new Runnable() {
		public void run() {
			double amp = mSensor.getAmplitude();
			updateDisplay(amp);
			handler.postDelayed(mPollTask, POLL_INTERVAL);

		}
	};

	private void stop() {
		handler.removeCallbacks(mSleepTask);
		handler.removeCallbacks(mPollTask);
		mSensor.stop();
		((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
				.setImageResource(R.drawable.amp1);
	}

	private Runnable mSleepTask = new Runnable() {
		public void run() {
			stop();
		}
	};

	// 改变语言条数的地方
	private void updateDisplay(double signalEMA) {

		switch ((int) signalEMA) {
		case 0:
		case 1:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp1);
			break;
		case 2:
		case 3:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp2);

			break;
		case 4:
		case 5:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp3);
			break;
		case 6:
		case 7:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp4);
			break;
		case 8:
		case 9:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp5);
			break;
		case 10:
		case 11:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp6);
			break;
		default:
			((ImageView) (ChatActivity.this.findViewById(R.id.volume)))
					.setImageResource(R.drawable.amp7);
			break;
		}
	}

	// 上传已经录制好的语音
	public void UpSound(String paths) {
		Utils.showProgress_hen(ChatActivity.this);
		if (startHaomiao != 0 || endHaomiao != 0) {
			miaoshu = (int) ((endHaomiao - startHaomiao) / 1000);
			endHaomiao = 0;
			startHaomiao = 0;
		} else {
			miaoshu = 0;
		}
		AjaxParams params = new AjaxParams();
		File file = new File(paths);
		if (file.exists()) {
			//    
		}
		try {
			params.put("info", file);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			   
		}
		FinalHttp fh = new FinalHttp();
		// fh.configTimeout(15000);
		// fh.configRequestExecutionRetryCount(3);
		fh.post(Constants.BadiUrl_1 + "Index/toUploadAmr", params,
				new AjaxCallBack<Object>() {
					Message message;
					Bundle bundle;

					@Override
					public void onLoading(long count, long current) {
						// TODO Auto-generated method stub
						super.onLoading(count, current);
						//    
						message = new Message();
						bundle = new Bundle();
						message.what = 6;
						bundle.putInt("msg", (int) count);
						message.setData(bundle);
						handler.sendMessage(message);
					}

					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						//    
						// Utils.ExitProgress_hen(context);
						//    
						if (t != null) {
							//    
						}

						Results results = Utils.checkResult_NNN(
								ChatActivity.this, (String) t);
						if (results != null
								&& !results.getRetmsg().equals("null")
								&& results.isRet() == true) {
							message = new Message();
							bundle = new Bundle();
							message.what = 5;
							bundle.putString("msg", results.getRetmsg());
							bundle.putInt("miaoshu", miaoshu);
							message.setData(bundle);
							handler.sendMessage(message);
						} else {
							handler.sendEmptyMessage(1);
						}
					}
				});
	}

	private void Chat_lists() {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				message_Models.clear();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("fid", id);
				map.put("page", Page);
				map.put("pageNum", "8");
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "chat/lists");
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					//    ("历史消息返回的数据是 :" + content);
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						try {
							message_Models = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Chat_History_Message_Model.class);
							System.out.println("chat"+results.getRetmsg());
							handler.sendEmptyMessage(8);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							   
						}
					} else {
						handler.sendEmptyMessage(7);
						if (Page > 1) {
							--Page;
						} else {
							Page = 1;
						}
					}
				} else {
					handler.sendEmptyMessage(1);
					if (Page > 1) {
						--Page;
					} else {
						Page = 1;
					}
				}
			}
		});
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		++Page;
		Chat_lists();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		Page = 1;
		Chat_lists();
	}

}
